package cuit.epoch.pymjl.security.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import cuit.epoch.pymjl.security.common.result.CommonResult;
import cuit.epoch.pymjl.security.common.result.PageResult;
import cuit.epoch.pymjl.security.common.result.Result;
import cuit.epoch.pymjl.security.common.result.ResultUtils;
import cuit.epoch.pymjl.security.common.utils.UUIDUtil;
import cuit.epoch.pymjl.security.common.utils.UploadImage;
import cuit.epoch.pymjl.security.entity.TShop;
import cuit.epoch.pymjl.security.mapper.TShopMapper;
import cuit.epoch.pymjl.security.service.TShopService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.List;

@RestController
public class TshopController {
    private final TShopService tShopService;
    private final TShopMapper tShopMapper;

    @Autowired
    public TshopController(TShopService tShopService, TShopMapper tShopMapper) {
        this.tShopService = tShopService;
        this.tShopMapper = tShopMapper;
    }

    //新增或修改
    @PostMapping("/shopmanage")
    public Result result(@RequestParam(value = "id", required = false) Integer id,
                         @RequestParam("username") String username,
                         @RequestParam("usernickname") String usernickname,
                         @RequestParam("phone") String phone,
                         @RequestParam("shopimg") MultipartFile file,
                         @RequestParam("shopimg02") MultipartFile file02,
                         @RequestParam("shopimg03") MultipartFile file03,
                         @RequestParam("quantity") String quantity,
                         @RequestParam("shoptext") String shoptext,
                         @RequestParam("campus") String campus,
                         @RequestParam("fulladdress") String fulladdress,
                         @RequestParam("academy") String academy,
                         @RequestParam("price") String price,
                         @RequestParam("shopname") String shopname,
                         @RequestParam("wxnamder") String wxnamder
    ) throws IOException {
        TShop tShop = new TShop();
        if (id != null) {
            tShop.setId(id);
            TShop tShop1 = tShopMapper.selectById(id);
            String shopimg = tShop1.getShopimg();
            String shopimg02 = tShop1.getShopimg02();
            String shopimg03 = tShop1.getShopimg03();
            try {
                UploadImage.sshSftpDel(shopimg);
                UploadImage.sshSftpDel(shopimg02);
                UploadImage.sshSftpDel(shopimg03);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
        tShop.setPhomenumber(phone);
        tShop.setPrice(price);
        tShop.setCampus(campus);
        tShop.setAcademy(academy);
        tShop.setQuantity(quantity);
        tShop.setShoptext(shoptext);
        tShop.setFulladdress(fulladdress);
        //重命名上传文件
        String newFileName = UUIDUtil.generate()+".jpg";
        String newFileName02 = UUIDUtil.generate()+".jpg";
        String newFileName03 = UUIDUtil.generate()+".jpg";
        //文件名保存到数据库
        tShop.setShopimg(newFileName);
        tShop.setShopimg02(newFileName02);
        tShop.setShopimg03(newFileName03);
        //将图片上传到服务器
        try {
            UploadImage.sshSftp(file.getBytes(), newFileName);
            UploadImage.sshSftp(file02.getBytes(), newFileName02);
            UploadImage.sshSftp(file03.getBytes(), newFileName03);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

        tShop.setUsername(username);
        tShop.setShopname(shopname);
        tShop.setUsernickname(usernickname);
        tShop.setWxid(wxnamder);
        boolean i = tShopService.saveOrUpdate(tShop);
        return i == true ? Result.suc() : Result.fall("新增或更新商品失败！");
    }
    //新增或修改
/*    @PostMapping("/shopmanage")
    public Result resultt(@RequestBody TShop tShop){
        boolean i = tShopService.saveOrUpdate(tShop);
        TShop tShop1 = new TShop();
        return i == true ? Result.suc() : Result.fall("新增或更新商品失败！");
    }*/


    //删除商品的接口
    @DeleteMapping("/deleteshop")
    public Result result(@RequestParam("id") Integer id) {
        //服务器删除图片
        TShop tShop = tShopMapper.selectById(id);
        String shopimg = tShop.getShopimg();
        String shopimg02 = tShop.getShopimg02();
        String shopimg03 = tShop.getShopimg03();
        try {
            UploadImage.sshSftpDel(shopimg);
            UploadImage.sshSftpDel(shopimg02);
            UploadImage.sshSftpDel(shopimg03);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        //数据库删除数据
        int i = tShopMapper.deleteById(id);
        return i == 1 ? Result.suc() : Result.fall("删除失败");
    }

    //修改商品状态
    @PutMapping("/shelvesshoportakedownshop")
    public Result result(@RequestBody TShop tShop) {
        TShop tShop1 = tShopMapper.selectById(tShop.getId());
        if (tShop1.getAudit() == 0) {
            return Result.fall("该商品还在审核！");
        } else if (tShop1.getAudit() == 1 && tShop1.getItemstatus() == 0) {
            tShop.setItemstatus(1);
            tShop.setShopstate("上架中");
            int i = tShopMapper.updateById(tShop);
            return i == 1 ? Result.suc("商品上架成功！") : Result.fall("修改失败！");
        } else if (tShop1.getAudit() == 1 && tShop1.getItemstatus() == 1) {
            tShop.setItemstatus(0);
            tShop.setShopstate("未上架");
            int i = tShopMapper.updateById(tShop);
            return i == 1 ? Result.suc("商品下架成功！") : Result.fall("修改失败！");
        }
        return null;
    }

/*    //获取用户管理商品的接口
    @GetMapping("/getmanageshop")
    public PageResult<TShop> products(@RequestParam int pageNum, @RequestParam int pageSize, @RequestParam String username) {
        Page<TShop> page = new Page<>(pageNum, pageSize);
        QueryWrapper<TShop> wrapper = new QueryWrapper<>();
        wrapper.like("username", username);
        Page<TShop> userList = tShopMapper.selectPage(page, wrapper);
        return new PageResult<>(userList, String.valueOf(page.getTotal()));
    }*/

    //获取用户管理商品的接口()
    @GetMapping("/getmanageshop")
    public Result productss(@RequestParam String username) {
        QueryWrapper<TShop> wrapper = new QueryWrapper<>();
        wrapper.like("username", username);
        List<TShop> userList = tShopMapper.selectList(wrapper);
        return Result.suc(userList);
    }
    @PutMapping("/konwmessage")
    public Result konwmessage(@RequestBody TShop tShop){
        LambdaUpdateWrapper<TShop> lambdaUpdateWrapper = new LambdaUpdateWrapper<>();
        lambdaUpdateWrapper.eq(TShop::getUsername, tShop.getUsername()).set(TShop::getMessageyesorno,1);
        int rows = tShopMapper.update(null, lambdaUpdateWrapper);
        System.out.println(rows);
        return rows!=0?Result.suc():Result.fall("更新已读失败");
    };
    //获取已经通过审批并且已经上架商品的接口
    @GetMapping("/getshop")
    public PageResult<TShop> getshop(@RequestParam int pageNum, @RequestParam int pageSize) {
        Page<TShop> page = new Page<>(pageNum, pageSize);
        QueryWrapper<TShop> wrapper = new QueryWrapper<>();
        wrapper.like("audit", 1);
        wrapper.like("itemstatus", 1);
        Page<TShop> userList = tShopMapper.selectPage(page, wrapper);
        return new PageResult<>(userList, String.valueOf(page.getTotal()));
    }
    //根据关键字进行模糊匹配，根据条件进行筛选
    @GetMapping("/search")
    public PageResult<TShop> searchKeyWord(@RequestParam int pageNum, @RequestParam int pageSize, @RequestParam String keyWord, @RequestParam(required = false) String xueyuan, @RequestParam(required = false) String xiaoqu) {
        Page<TShop> page = new Page<>(pageNum, pageSize);
        QueryWrapper<TShop> wrapper = new QueryWrapper<>();
        if (xueyuan != null){
            wrapper.eq("academy",xueyuan);
        }
        if (xiaoqu != null){
            wrapper.eq("campus",xiaoqu);
        }
        wrapper.eq("audit", 1);
        wrapper.eq("itemstatus", 1);
        wrapper.like("shopname", keyWord);
        Page<TShop> userList = tShopMapper.selectPage(page, wrapper);
        return new PageResult<>(userList, String.valueOf(page.getTotal()));
    }
    //管理员下架商品
    @PutMapping("/Removalofproducts")
    @PreAuthorize("hasAuthority('shopmanage')")
        public Result Removalofproducts(@RequestBody TShop tShop){
        TShop tShop01 = new TShop();
        tShop.setAudit(0);
        tShop.setShopstate("未上架");
        QueryWrapper<TShop> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id",tShop.getId());
        int i = tShopMapper.update(tShop,queryWrapper);
        return i==1?Result.suc("驳回成功！"):Result.fall("驳回失败！！");
    }

    //获取已经上传待审批的商品接口
    @GetMapping("/getapproveshop")
    @PreAuthorize("hasAuthority('shopmanage')")
    public Result getApproveshop() {
        QueryWrapper<TShop> wrapper = new QueryWrapper<>();
        wrapper.like("audit", 0);
        List<TShop> list =  tShopMapper.selectList(wrapper);
        return Result.suc(list);
    }

    //获取已经商品审批结果的消息接口
    @GetMapping("/getshopnewmessage")
    public Result getshopnewmessage() {
        QueryWrapper<TShop> wrapper = new QueryWrapper<>();
        wrapper.like("audit", 0);
        List<TShop> list =  tShopMapper.selectList(wrapper);
        return Result.suc(list);
    }

    //管理员审批商品接口
    @GetMapping("/shopmanage")
    @PreAuthorize("hasAuthority('shopmanage')")
    public CommonResult<String> test() {
        return ResultUtils.success("test");
    }

    //审批通过商品
    @PutMapping("/approveshop")
    @PreAuthorize("hasAuthority('shopmanage')")
    public Result result02(@RequestBody TShop tShop){
        int i = tShopMapper.updateFieldById(tShop.getId());
        return i ==1?Result.suc("审批通过成功！"):Result.fall("审批通过失败！");
    }

    //驳回商品
    @PutMapping("/shopdismissal")
    @PreAuthorize("hasAuthority('shopmanage')")
    public Result result(@RequestParam("id") Integer id,
                         @RequestParam("remark") String remark){
        TShop tShop = new TShop();
        tShop.setRemark(remark);
        QueryWrapper<TShop> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id",id);
        int i = tShopMapper.update(tShop, queryWrapper);
        return i==1?Result.suc("驳回成功！"):Result.fall("驳回失败！！");
    }
}

